<template>
  <div id="postindex">
    <nav>
      <van-sticky>
        <div id="postindex-nav">
          <van-icon
            name="arrow-left"
            id="postindex-nav-back"
            size="23px"
            @click="returnPostList()"
          />
          <span id="postindex-nav-span">详情</span>
          <van-icon name="more-o" id="postindex-nav-more" size="23px" />
        </div>
      </van-sticky>
    </nav>
    <article>
      <section>
        <post-owner
          :userimg="myimg"
          :postimg="post_imgs"
          :ownername="ownername"
          :time="time"
          :ownercontent="ownercontent"
          :tag="tag"
        >
        </post-owner>
      </section>
      <section id="comment">
        <div id="commet-div">
          <ul>
            <li v-for="(item, index) in comment_items" :key="index">
              <post-item
                v-if="item.avatar != null"
                :comment_content="item.content"
                :comment_name="item.name"
                :comment_time="getTimeBefore(item.time)"
                :comment_userimg="item.avatar.avatar"
                :comment_index="item.index"
                :comment_children="item.children"
                :comment_position="index"
                :comment_like="item.like"
                :comment_liked="item.liked"
                :comment_imgs="item.img"
                @addChild="addChild"
                @changeLike="changeLike"
              >
              </post-item>
              <hr width="350" />
            </li>
          </ul>
        </div>
      </section>
    </article>
    <footer>
      <post-footer
        @addMain="addMain"
        :author="ownername"
        :content="ownercontent"
      ></post-footer>
    </footer>
  </div>
</template>

<script>
import { Image, NavBar, Icon, Tag, Sticky, Toast } from "vant";
import PostOwner from "@/components/BBSModuleComponents/PostOwner.vue";
import CommentItem from "@/components/CommentModuleCommponents/PostCommentItem.vue";
import PostFooter from "@/components/CommentModuleCommponents/PostFooter.vue";
import {getPostComment,addPostComment} from "@/api/commentAPI"
import { changeLike } from "@/api/BBSModuleAPI/BBSLike.js";
import { formatTime } from "@/utils/formatTime";
import { showStatusTip } from "@/utils/loginStatus.js";

export default {
  data() {
    return {
      ownercontent: "",
      ownername: "",
      time: "",
      comment_items: [],
      like_items: [],
      post_id: "",
      post_imgs: [],
      myimg: "",
      tag: "",
    };
  },
  components: {
    [Image.name]: Image,
    [NavBar.name]: NavBar,
    [Icon.name]: Icon,
    [Tag.name]: Tag,
    [Sticky.name]: Sticky,
    [Toast.name]: Toast,
    "post-owner": PostOwner,
    "post-item": CommentItem,
    "post-footer": PostFooter,
  },
  created() {
    document.documentElement.scrollTop = 0;

    //获取跨页面传参
    this.comment_id = this.$route.params.post_id;
    this.ownercontent = this.$route.params.info;
    this.ownername = this.$route.params.username;
    this.tag = this.$route.params.tag;
    this.time = this.$route.params.time;
    this.myimg = this.$route.params.avatar;
    this.post_imgs = this.$route.params.info_img;
    //初始化
    const init = async () => {
      const data = await getPostComment({
        post_id: this.comment_id,
        username: sessionStorage.getItem("username"),
      });
      if (data.result != null) {
        this.comment_items = data.result;
        this.like_items = data.likes;
        //对当前用户是否点赞给每个评论打标签
        for (let j = 0; j < this.like_items.length; j++)
          for (let i = 0; i < this.comment_items.length; i++) {
            console.log("time", this.getTimeBefore(this.comment_items[i].time));
            if (this.comment_items[i].index == this.like_items[j].comment_id) {
              this.comment_items[i].liked = true;
            }
            for (let k = 0; k < this.comment_items[i].children.length; k++) {
              if (
                this.comment_items[i].children[k].index ==
                this.like_items[j].comment_id
              ) {
                this.comment_items[i].children[k].liked = true;
              }
            }
          }
      }
    };
    init();
  },
  methods: {
    //格式化时间
    getTimeBefore(time) {
      const str = formatTime(time);
      let minute = 0;
      return minute >= 0 ? str : 0;
    },
    //添加子评论
    //it_to: 对哪个评论进行评论
    //content: 评论内容
    addChild(it_to, content) {
      const add = async () => {
        const data = await addPostComment({
          toId: this.comment_id,
          username: sessionStorage.getItem("username"),
          info: content,
          info_img: [],
          isChild: 1,
          told_main: it_to,
        });

        this.comment_items = data.result;
        console.log("after_add", this.comment_items);
      };
      add();
    },
    //添加评论
    //content: 评论内容
    //images: 评论的图片路径列表
    addMain(content, images) {
      const addmain = async () => {
        const data = await addPostComment({
          toId: this.comment_id,
          username: sessionStorage.getItem("username"),
          info: content,
          info_img: images,
          isChild: 0,
          told_main: null,
        });

        this.comment_items = data.result;
        console.log("after_add", this.comment_items);
      };
      addmain();
    },
    //返回列表页面
    returnPostList() {
      history.back();
    },
    
    //点赞或者取消点赞
    changeLike(index, pos) {
      if (sessionStorage.getItem("username") == null) {
        showStatusTip(null, "\n游客登陆无法点赞");
      } else if (
        sessionStorage.getItem("username") != null &&
        sessionStorage.getItem("visitor") == "true"
      ) {
        showStatusTip(null, "无法点赞");
      } else {
        const change = async () => {
          const data = await changeLike({
            user_name: sessionStorage.getItem("username"),
            comment_id: index,
          });
          let back = data.back;
          //根据返回结果判断是点赞还是取消点赞，然后找到对应的评论在本地改变数字，不用重新获取一遍了
          if (index == this.comment_items[pos].index) {
            if (back == 1) {
              this.comment_items[pos].like += 1;
            } else {
              this.comment_items[pos].like -= 1;
            }
          }
          for (let i = 0; i < this.comment_items[pos].children.length; i++) {
            if (index == this.comment_items[pos].children[i].index) {
              if (back == 1) {
                this.comment_items[pos].children[i].like += 1;
              } else {
                this.comment_items[pos].children[i].like -= 1;
              }
            }
          }
        };
        change();
      }
    },
  },
};
</script>

<style scoped>
#postindex {
  background-color: rgb(236, 236, 236);
}

#postindex-nav {
  padding-top: 5px;
  padding-bottom: 10px;
  display: flex;
  justify-content: space-between;
  border-bottom: rgb(165, 165, 165) solid 1px;
  background-color: rgb(238, 238, 238);
}

#postindex-nav-back {
  margin-left: 10px;
  margin-top: 5px;
}

#postindex-nav-span {
  margin-top: 3px;
  font-size: 20px;
  font-weight: bold;
  color: #1989fa;
}

#postindex-nav-more {
  margin-right: 10px;
  margin-top: 5px;
}

article {
  border-top: rgb(161, 161, 161) solid 1px;
}

section {
  border-bottom: rgb(155, 155, 155) solid 1px;
  background-color: rgb(255, 255, 255);
  margin-top: 8px;
}

#comment {
  min-height: 500px;
}

#commet-div {
  margin-top: 8px;
}

ul {
  list-style: none;
  text-decoration: none;
  overflow: scroll;
  overflow-y: hidden;
}

ul li {
  list-style: none;
  text-decoration: none;
}

hr {
  height: 1px;
  color: #987cb9;
  size: 1;
}

footer {
  margin-bottom: 50px;
}
</style>
